package com.earthquake.monitor_system.controller.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.earthquake.monitor_system.controller.User;
import com.earthquake.monitor_system.controller.resultType.UserInfoType;
import com.earthquake.monitor_system.excption.businessSystemException;
import com.earthquake.monitor_system.service.impl.UserImpl;
import com.earthquake.monitor_system.utils.status;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

    @Component
    public class ProjectInterceptor implements HandlerInterceptor {
        @Autowired
        private UserImpl userImpl;
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String token = request.getHeader("token");
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }
            if(StrUtil.isAllBlank(token)){
                throw new businessSystemException("用户不存在，请重新登录!", status.STATUS_401);
            }
            String id;
            try {
                id = JWT.decode(token).getAudience().get(0);
            } catch (JWTDecodeException j) {
                throw new businessSystemException("token不正确，请不要通过非法手段创建token",status.STATUS_401);
            }
            UserInfoType byId = userImpl.getById(Integer.parseInt(id));
            //查询数据库，看看是否存在此用户，方法要自己写
            if (byId == null) {
                throw new businessSystemException("用户不存在，请重新登录",status.STATUS_401);
            }
            // 验证 token
            try {
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(byId.getUsername())).build();
                jwtVerifier.verify(token);
            }catch (TokenExpiredException e) {
                throw new businessSystemException("token过期或不正确，请重新登录",status.STATUS_401);
            }
                return true;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("postHandle");
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("afterCompletion");
        }

    }
